var basePath = $("#basePath").val();
$(document).ready(function (){
    menuCss("医院");

    var url = basePath + "/base/queryProvince";
    publicAjax(url,"POST",{},function (data) {
            if(data.ret == 200){
                initQueryHospitalData(data.data);
            }else {
                flavrShowByTime(data.msg,null,"danger",false);
                return;
            }
    });

    $("#queryForm").find("[name='cityId']").val(null);
    $("#queryForm").find("[name='cityId']").select2({
        language: 'zh-CN',
        placeholder: '请选择城市',
        allowClear: true});
    $("#queryForm").find("[name='areaId']").val(null);
    $("#queryForm").find("[name='areaId']").select2({
        language: 'zh-CN',
        placeholder: '请选择区域',
        allowClear: true});

    queryHospitalList(0,10);
    $("#show-count").change(function(){
        queryHospitalList(0,$("#show-count").val());
    })
    bindEvent();
    //initModel();
    $('input[type="radio"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });

});


function initQueryHospitalData(object){
        var province = $("#queryForm").find("[name='provinceId']");
        $(province).html("");
        var html = "";
        $.each(object,function (index,item) {
            html += "<option value='"+item.provinceId+"'>"+item.province+"</option>"
        });
        $(province).html(html);
        $(province).val(null);
        $(province).select2({language: 'zh-CN',placeholder: "请选择省份",allowClear: true});
}


function bindEvent() {
    $("#search").click(function (){
        queryHospitalList(0,10)
    });

    $("#add").click(function (){
        initAddHospitalData();
        $("#add-modal").iziModal("open",this);
    });

    $("#saveHospital").click(function (){
        saveHospital();
    });

    $("#edit").click(function (){
        initAddHospitalData();
        editHospitalInitData();
    });

    $("#import").click(function (){
        location.href=basePath+"/hospital/import";
    });

    $("#queryForm").find("[name='provinceId']").change(function (){
        var value = $(this).val();
        if(value == null || value == ""){
            $("#queryForm").find("[name='cityId']").html("");
            $("#queryForm").find("[name='areaId']").html("");
            return;
        }
        var url = basePath + "/base/queryCity";
        publicAjax(url,"POST",{"provinceId":value},function (data) {
            var city = $("#queryForm").find("[name='cityId']");
            $(city).html("");
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.cityId+"'>"+item.city+"</option>"
            });
            $(city).html(html);
            $(city).val(null);
            $(city).select2({language: 'zh-CN',placeholder: "请选择城市",allowClear: true});
        })
    });

    $("#queryForm").find("[name='cityId']").change(function (){
        var value = $(this).val();
        if(value == null || value == ""){
            $("#queryForm").find("[name='areaId']").html("");
            return;
        }
        var url = basePath + "/base/queryArea";
        publicAjax(url,"POST",{"cityId":value},function (data) {
            var area = $("#queryForm").find("[name='areaId']");
            $(area).html("");
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.areaId+"'>"+item.area+"</option>"
            });
            $(area).html(html);
            $(area).val(null);
            $(area).select2({language: 'zh-CN',placeholder: "请选择区域",allowClear: true});
        })

    });
}


function queryHospitalList(start,limit) {
    var json = {};
    json.start = start;
    json.end = $("#show-count").val();
    var allName = $("#queryForm").find("[name='allName']").val();
    var provinceId = $("#queryForm").find("[name='provinceId']").val();
    var cityId = $("#queryForm").find("[name='cityId']").val();
    var areaId = $("#queryForm").find("[name='areaId']").val();
    json.allName = allName;
    json.provinceId = provinceId;
    json.cityId = cityId;
    json.areaId = areaId;
    var url = basePath + "/hospital/queryHospitalList";
    publicAjax(url,"POST",json,function (data) {
        if(data.ret == 200){
            bindHospitalList(data.data.list);
            $("#total-count").text(data.data.count);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    })
}

function bindHospitalList(obj){
    $("#hospital_table").html("");
    var html = "";
    if(obj == null || obj.length == 0){
        html="<tr><td class='text-center' colspan='12'>暂无数据</td></tr>";
    }

    $.each(obj,function (index,item) {
        html+="<tr><td class='text-center text-muted'>"+(index+1)+"</td>" +
            "<td class='text-center text-muted'>" +
                "<input type='checkbox' class='flat-green' name='one' value='"+item.hospitalId+"'> " +
                "<button name='lnglat' type='button' class='btn btn-info btn-xs' data-toggle='tooltip' title='设置经纬度'>" +
                    "<span name='hospital' class='hide' data-id='"+item.hospitalId+"' " +
                        "data-city='" + (item.region || "") + "' " +
                        "data-xy='" + (item.mapX && item.mapY ? item.mapX + ',' + item.mapY : '') + "'>" +
                        item.hospitalName +
                    "</span>" +
                    "<i class='fa fa-cog'></i>" +
                "</button>" +
            "</td>" +
            "<td class='text-muted'>"+(item.hospitalName==null?'':item.hospitalName)+"</td>" +
            "<td class='text-muted'>"+(item.hospitalCode==null?'':item.hospitalCode)+"</td>" +
            "<td class='text-muted'>"+(item.region==null?'':item.region)+"</td>" +
            "<td class='text-muted'>"+(item.hospitalContacts==null?'':item.hospitalContacts)+"</td>" +
            "<td class='text-muted'>"+(item.hospitalPhone==null?'':item.hospitalPhone)+"</td>" +
            "<td class='text-muted'>"+(item.address==null?'':item.address)+"</td>" +
            "</tr>"
    });
    $("#hospital_table").html(html);
    initDomCss();
    $("button[name='lnglat']").click(function(){
        new SetLngLat($(this).find("span[name=hospital]").html(),
            $(this).find("span[name=hospital]").data().id,
            $(this).find("span[name=hospital]").data().city,
            $(this).find("span[name=hospital]").data().xy,
            function () {
                queryHospitalList(0,10);
            });//查询医院信息
    });
}

function initDomCss(){
    $('input[type="checkbox"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });

    $("input[name='one']").on('ifChecked', function(event){
        var current = $(this).parents("tr").index();
        $("[name='one']:checked").each(function(i){
            if($(this).parents("tr").index()!=current){
                $(this).iCheck('uncheck');
            }
        });
    });
}

    $("#add-modal").iziModal({
        title: "编辑医院",
        headerColor: '#00c0ef',
        rtl: false,
        width: 800,
        zindex: 1044,
        group: '',
        loop: false,
        history: false,
        restoreDefaultContent: false,
        autoOpen: false, // Boolean, Number
        bodyOverflow: false,
        fullscreen: true,
        openFullscreen: false,
        closeOnEscape: true,
        onOpening: function () {
            //initAddHospitalData();
            validator();
        },
        onOpened: function () {
        },
        onClosing: function () {
        },
        onClosed: function () {
            $("#add-update-from").find("[name='hospitalId']").val(null);
            $('#add-update-from')[0].reset();
            $("#add-update-from").find("[name='cityId']").html("");
            $("#add-update-from").find("[name='areaId']").html("");
            $("#add-update-from").data('bootstrapValidator').destroy();

        }
    });


function validator(){
    $('#add-update-from').bootstrapValidator({
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        live: 'enabled',
        message: '非有效值',
        fields: {
            hospitalName: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            }
        }
    });
}


function initAddHospitalData(){

        $('input[type="radio"].flat-green').iCheck({
            checkboxClass: 'icheckbox_flat-green',
            radioClass: 'iradio_flat-green'
        });

        var province = $("#add-update-from").find("[name='provinceId']");
        var city = $("#add-update-from").find("[name='cityId']");
        var area = $("#add-update-from").find("[name='areaId']");

        $(province).html($("#queryForm").find("[name='provinceId']").html());
        $(province).val(null);

        $("#add-update-from").find("[name='provinceId']").select2({language: 'zh-CN',placeholder: "请选择",allowClear: true});
        $("#add-update-from").find("[name='cityId']").select2({language: 'zh-CN',placeholder: "请选择",allowClear: true});
        $("#add-update-from").find("[name='areaId']").select2({language: 'zh-CN',placeholder: "请选择",allowClear: true});


        $(province).change(function (){
            provinceChang(null,function (){
                $("#add-update-from").find("[name='cityId']").select2({language: 'zh-CN',placeholder: "请选择",allowClear: true});
            });
        });

        $(city).change(function (){
            cityChang(null,function (){
                $("#add-update-from").find("[name='areaId']").select2({language: 'zh-CN',placeholder: "请选择",allowClear: true});
            });
        });
}

function provinceChang(cityId,fn){
    var value = $("#add-update-from").find("[name='provinceId']").val();
    if(value == null || value == ""){
        $("#add-update-from").find("[name='cityId']").html("");
        $("#add-update-from").find("[name='areaId']").html("");
        return;
    }
    var url = basePath + "/base/queryCity";
    publicAjax(url,"POST",{"provinceId":value},function (data) {
        $("#add-update-from").find("[name='cityId']").html("");
        var html = "";
        $.each(data.data,function (index,item) {
            if(item.cityId == cityId){
                html += "<option value='"+item.cityId+"' selected>"+item.city+"</option>"
            }else{
                html += "<option value='"+item.cityId+"'>"+item.city+"</option>"
            }

        });
        $("#add-update-from").find("[name='cityId']").html(html);
        $("#add-update-from").find("[name='cityId']").val(null);
        fn();
    })

}

function cityChang(areaId,fn){
    var value = $("#add-update-from").find("[name='cityId']").val();
    if(value == null || value == ""){
        $("#add-update-from").find("[name='areaId']").html("");
        return;
    }
    var url = basePath + "/base/queryArea";
    publicAjax(url,"POST",{"cityId":value},function (data) {
        $("#add-update-from").find("[name='areaId']").html("");
        var html = "";
        $.each(data.data,function (index,item) {
            if(item.areaId == areaId){
                html += "<option value='"+item.areaId+"' selected>"+item.area+"</option>"
            }else{
                html += "<option value='"+item.areaId+"'>"+item.area+"</option>"
            }

        });
        $("#add-update-from").find("[name='areaId']").html(html);
        $("#add-update-from").find("[name='areaId']").val(null);
        fn();
    })

}


var bl = false;
function saveHospital() {
    $('#add-update-from').bootstrapValidator('validate');
    if($('#add-update-from').data('bootstrapValidator').isValid()){
        if(!bl){
            bl = true;
            var url = basePath+"/hospital/addOrUpdateHospital"
            publicAjax(url,"POST",$("#add-update-from"),function (data) {
                if(data.ret == 200){
                    flavrShowByTime(data.msg,null,"success",false);
                    queryHospitalList(0,10);
                    $("#add-modal").iziModal("close", this);
                    bl=false;
                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                    bl=false;
                }
            })
        }
    }
}


function editHospitalInitData(){
    if(!$("input[name='one']:checked").length){
        flavrShowByTime("请选择一个医院", null, "danger", false);
        return;
    }
    var json = {"hospitalId":$("input[name='one']:checked").val()};
    var url=basePath+"/hospital/queryHospitalInfo";
    publicAjax(url,"POST",json,function (data) {
        bindHospitalInfo(data.data);
    });
}


function bindHospitalInfo(obj){

        $("#add-update-from").find("[name='hospitalId']").val(obj.hospitalId);
        $("#add-update-from").find("[name='hospitalName']").val(obj.hospitalName);
        $("#add-update-from").find("[name='hospitalCode']").val(obj.hospitalCode);
        $("#add-update-from").find("[name='address']").val(obj.address);
        $("#add-update-from").find("[name='hospitalContacts']").val(obj.hospitalContacts);
        $("#add-update-from").find("[name='hospitalPhone']").val(obj.hospitalPhone);
        $("#add-update-from").find("[name='remark']").val(obj.remark);

        $("#add-update-from").find("[name='provinceId']").val(obj.provinceId);
        showText($("#add-update-from").find("[name='provinceId']"));

        provinceChang(obj.cityId,function (){
            $("#add-update-from").find("[name='cityId']").val(obj.cityId);
            showText( $("#add-update-from").find("[name='cityId']"));

            cityChang(obj.areaId,function (){
                $("#add-update-from").find("[name='areaId']").val(obj.areaId).change();
                showText( $("#add-update-from").find("[name='areaId']"));
            });
        });

        $("input[type='radio'][name='isDel'][value='"+obj.isDel+"']").attr("checked",true);
        $("input[type='radio'][name='isDel'][value='"+obj.isDel+"']").addClass("checked");
        $('input[type="radio"].flat-green').iCheck({
            checkboxClass: 'icheckbox_flat-green',
            radioClass: 'iradio_flat-green'
        });
        $("#add-modal").iziModal("open",this);

}

function showText(obj){
    var text2 =$(obj).find("option:selected").text();
    $(obj).select2({language:'zh-CN', placeholder:text2, allowClear:true});
}

//分页
function Pagination(total,limit,current){
    $('.M-box3').empty();
    $('.M-box3').pagination({
        totalData:total,
        showData:limit,//数据总数totalData和每页显示的条数showData必须同时配置，否则默认使用总页数pageCount;limit可选值 5 10 20 50
        //pageCount:50,
        current:current,
        jump:true,
        coping:true,
        homePage:'首页',
        endPage:'末页',
        prevContent:'上页',
        nextContent:'下页',
        callback:function(index){
          start = (index.getCurrent()-1)*limit;
          limit = index.getShowData();
          queryHospitalList(start,limit);
        }
  });
}